// .vuepress/client.js
import { defineClientConfig } from "@vuepress/client";
import { nextTick, onMounted, onUnmounted } from "vue";
import mermaid from "mermaid";

// 1️⃣ 只初始化一次
mermaid.initialize({
  startOnLoad: false,
  theme: "default",
});

class PagerMermaid {
  constructor() {}

  renderMermaid_bak() {
    console.log("into renderMermaid");
    if (typeof window === "undefined") return;
    nextTick(() => {
      const els = document.querySelectorAll(".mermaid");
      console.log(els);
      if (els.length) mermaid.init(els);
    });
  }
  async renderMermaid() {
    console.log("into renderMermaid");
    if (typeof window === "undefined") return;
    nextTick(async () => {
      const mermaidContainers = document.querySelectorAll(
        "div.mermaid-container"
      );
      //console.log("mermaidContainers:", mermaidContainers);

      if (!mermaidContainers || mermaidContainers.length === 0) {
        //console.log("No mermaid containers found");
        return;
      }

      for (const container of mermaidContainers) {
        console.log("Processing container:", container);

        // 检查 container 是否有效
        if (!container) {
          //console.error("Invalid container element");
          continue;
        }

        const pre = container.querySelector("pre.mermaid");

        // 检查 pre 元素是否存在
        if (!pre) {
          //console.error("No pre.mermaid element found in container");
          continue;
        }

        const diagram = pre.textContent;
        //console.log("diagram:", diagram);

        // 检查 diagram 是否为空
        if (!diagram || diagram.trim() === "") {
          //console.error("Empty diagram content");
          continue;
        }

        try {
          // 使用 mermaid.render 获取 SVG 代码
          const { svg } = await mermaid.render(
            `mermaid-${Date.now()}`,            
            diagram.trim()
          );

          // 将 SVG 代码插入到容器中
          container.innerHTML = svg;
        } catch (error) {
          console.error("Error during mermaid rendering:", error);
        }
      }
    });
  }
  zoomIn() {}
}

let pagerMermaid = new PagerMermaid();

export default defineClientConfig({
  enhance({ app, router }) {
    // 2️⃣ 路由切换后渲染
    router.afterEach(() => {
      setTimeout(() => {
        pagerMermaid.renderMermaid();
      }, 1000 * 2);
    });
  },

  setup() {
    // 3️⃣ 第一次挂载后渲染
    pagerMermaid.renderMermaid();

    // 3️⃣ 监听浏览器的 popstate 事件（后退/前进按钮）
    const handlePopState = () => {
      pagerMermaid.renderMermaid();
    };
    onMounted(() => {
      window.addEventListener("popstate", handlePopState);
    });
    onUnmounted(() => {
      window.removeEventListener("popstate", handlePopState);
    });
  },
});
